/**
 * 文件上传相关 API
 */
import axios from 'axios'

const baseURL = import.meta.env.VITE_API_BASE || 'http://localhost:7002'

/**
 * 上传单个文件到七牛云
 * @param {File} file - 文件对象
 * @param {Function} onProgress - 上传进度回调
 * @returns {Promise<Object>} 上传结果
 */
export const uploadFile = async (file, onProgress) => {
  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await axios.post(`${baseURL}/api/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          onProgress(percentCompleted)
        }
      },
    })

    if (response.data.code === 0) {
      return {
        success: true,
        data: response.data.data,
      }
    } else {
      throw new Error(response.data.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传文件失败:', error)
    throw error
  }
}

/**
 * 批量上传文件到七牛云
 * @param {Array<File>} files - 文件对象数组
 * @param {Function} onProgress - 上传进度回调
 * @returns {Promise<Object>} 上传结果
 */
export const uploadFiles = async (files, onProgress) => {
  const formData = new FormData()
  files.forEach((file) => {
    formData.append('files', file)
  })

  try {
    const response = await axios.post(`${baseURL}/api/upload/batch`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          onProgress(percentCompleted)
        }
      },
    })

    if (response.data.code === 0) {
      return {
        success: true,
        data: response.data.data,
      }
    } else {
      throw new Error(response.data.msg || '批量上传失败')
    }
  } catch (error) {
    console.error('批量上传文件失败:', error)
    throw error
  }
}

/**
 * 获取七牛云上传 token
 * @returns {Promise<Object>} token 信息
 */
export const getQiniuUploadToken = async () => {
  try {
    const response = await axios.get(`${baseURL}/api/upload/token`)

    if (response.data.code === 0) {
      return {
        success: true,
        data: response.data.data,
      }
    } else {
      throw new Error(response.data.msg || '获取上传凭证失败')
    }
  } catch (error) {
    console.error('获取上传 token 失败:', error)
    throw error
  }
}

